<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/11/28
 * Time: 15:27
 */

namespace app\adminapiv3\service;


use app\adminapiv3\service\platform_manage\ServerAuthService;
use app\common\model\RivestCipher;
use app\common\service\platform_manage\account\ServerUserService;


class InstallService extends BaseService
{

    public function online($authRes)
    {
        $authServer = new ServerAuthService();

        $authData = $authRes['data'];
        foreach ($authData as $k => $v){
            $authServer->checkData($v);
            $authServer->checkLocal($v);
        }

        file_put_contents('./Install/auth.json', json_encode($authData));
    }

    /**
     * @name 离线授权
     * @param $file
     * @author wx
     * @date 2019/11/29 10:18
     */
    public function offline($file)
    {
        //1. 上传文件
        $uploadServer = new Upload();
        $uploadAuthDir = '../runtime/Upload/Auth';
        $uploadRes = $uploadServer->upload($file, $uploadAuthDir,'key',5*1024*1024);

        if($uploadRes['code'] != 0){
            $this->setError($this->CODE_FAIL, $uploadRes['msg']);
            return false;
        }

        //2. 解密文件
        $authFile = $uploadRes['path'].$uploadRes['file_name'];
        $rc4Server = new RivestCipher();
        $authServer = new ServerAuthService();

        $content = file_get_contents($authFile);
        $authInfo = $rc4Server->decrypt($content);

        if(!$authInfo){
            $this->setError($this->CODE_FAIL, '错误的授权文件');
            return false;
        }


        foreach ($authInfo as $k => $v){
            $authServer->checkData($v);

            $authServer->checkLocal($v);

            $nowTime = $v['stime'];

            //检测授权时间
            $authServer->checkAuthTime($v, $nowTime);

        }


        //4. 将授权信息组装成一条信息放在临时授权文件中
        $authData['stime'] = $nowTime;

        file_put_contents('./Install/auth.json',json_encode($authInfo));
        file_put_contents('./Install/system_time.json', json_encode($authData));

        //5. over
        return true;
    }


    /**
     * @name 安装添加系统管理员
     * @param $data
     * @author wx
     * @date 2019/11/28 15:30
     */
    public function adduser($data)
    {

        //1. 添加系统管理员
        $adminSalt = createSalt(6);
        $passwordServer = new Password();

        $data['password'] = $passwordServer->encrypt($data['password'], $adminSalt);
        $data['salt'] = $adminSalt;
        $data['reg_ip'] = $_SERVER['REMOTE_ADDR'];
        $data['ctime'] = time();
        $data['last_login_ip'] = '';
        $data['last_login_time'] = 0;
        $data['level'] = 1;

        $userServer = new ServerUserService();

        $adminInfo = $userServer->findData(['level' => 1]);
        if(empty($adminInfo)){
            $userServer->add($data);
        }else{
            $userServer->modify(['id' => $adminInfo['id']], $data);
        }

        return true;
    }

    /**
     * @name 逻辑处理
     * @param $ip
     * @param $port
     * @author wx
     * @date 2019/12/16 10:34
     */
    public function addProxy($ip, $module, $mysqlIp)
    {
        //1. 获取授权类型
        $content = file_get_contents('./Install/auth.json');
        $arr = json_decode($content, true);

        //端口
        $portArr = [
            'netfilter' => 9012,
            'proxy' => 9013,
        ];

        foreach ($arr as $k => $v){
            $mode = $v['mode'];
        }


        if ($mode == 2) {//1单机版,2高可用版
            if(empty($module)){
                returnErrJson($this->CODE_FAIL, '后端IP必须填写');
            }

            $moduleArr = json_decode($module,true);
        }

        $mysqlIp = '127.0.0.1';

        //测试数据库连接
        $databaseConf = config('database.');

        //连接数据库测试
        $link = @mysqli_connect($mysqlIp, $databaseConf['username'], $databaseConf['password'],$databaseConf['database'], $databaseConf['hostport']);

        if (!$link){
            $this->setError($this->CODE_FAIL, '数据库连接失败!');
            return false;
        }

        $insertData = array();

        if($mode == 1){//标准版
            foreach ($portArr as $type => $port){
                $tmp['ip'] = $ip;
                $tmp['type'] = $type;
                $tmp['port'] = $port;
                $tmp['used'] = 0;
                $tmp['ip_type'] = 2;
                $insertData[] = $tmp;
            }
        }else{//分布式版
            foreach ($moduleArr as $k => $v){
                if(!empty($v['backend_ip'])){
                    $ipArr = explode(',',$v['backend_ip']);
                    foreach ($ipArr as $backendIp){
                        $temp['ip'] = $backendIp;
                        $temp['type'] = $v['type'];
                        $temp['port'] = $portArr[$v['type']];
                        $temp['used'] = 0;
                        $temp['ip_type'] = 3;
                        $insertData[] = $temp;
                    }
                }
            }

        }

        $php = [
            [ 'ip' => $mysqlIp, 'type' => 'mysql', 'port' => '9008', 'used' => 0,'ip_type' => 4 ],//mysql
            [ 'ip' => $ip, 'type' => 'php', 'port' => '9009', 'used' => 0,'ip_type' => 1 ],//php
            [ 'ip' => $ip, 'type' => 'client', 'port' => '9011', 'used' => 0,'ip_type' => 2 ],//client
            [ 'ip' => $ip, 'type' => 'hgshield', 'port' => '9014', 'used' => 0,'ip_type' => 2 ],//hgshield
        ];

        $allInstertData = array_merge($php, $insertData);

        //1. 清除原来的配置
        $server = new  \app\common\service\platform_manage\ServerProxyService();
        $server->clear();

        //2. 添加现有配置
        $server->addAll($allInstertData);
    }




}